<?php

require_once __DIR__ . '/../vendor/autoload.php';

use Kunfeng\Dify\Client\DifyClientFactory;
use Kunfeng\Dify\Enum\ResponseMode;
use Kunfeng\Dify\Model\Chat\ChatMessage;
use Kunfeng\Dify\Model\DifyConfig;
use Kunfeng\Dify\Callback\ChatStreamCallback;

// 配置
$baseUrl = 'https://api.dify.ai/v1';
$apiKey = 'your-api-key-here';

echo "=== Dify PHP 客户端高级使用示例 ===\n\n";

// 1. 使用配置创建客户端
echo "1. 使用配置创建客户端...\n";

$config = DifyConfig::builder()
    ->baseUrl($baseUrl)
    ->apiKey($apiKey)
    ->connectTimeout(10000)
    ->readTimeout(120000)
    ->writeTimeout(60000)
    ->httpOptions([
        'verify' => false,
        'timeout' => 30
    ])
    ->build();

$client = DifyClientFactory::createClientFromConfig($config);
echo "✓ 使用配置创建客户端成功\n\n";

// 2. 会话管理示例
echo "2. 会话管理示例...\n";

$chatClient = DifyClientFactory::createChatClient($baseUrl, $apiKey);

// 创建新会话
$message1 = ChatMessage::create('你好，我想了解人工智能', 'user-123')
    ->withResponseMode(ResponseMode::BLOCKING);

try {
    $response1 = $chatClient->sendChatMessage($message1);
    $conversationId = $response1->getConversationId();
    echo "✓ 创建会话成功，会话ID: " . $conversationId . "\n";
    
    // 继续对话
    $message2 = ChatMessage::create('请详细介绍一下机器学习', 'user-123')
        ->withConversationId($conversationId)
        ->withResponseMode(ResponseMode::BLOCKING);
    
    $response2 = $chatClient->sendChatMessage($message2);
    echo "✓ 继续对话成功: " . substr($response2->getAnswer(), 0, 100) . "...\n";
    
    // 获取会话历史
    $messages = $chatClient->getMessages($conversationId, 'user-123', null, 10);
    echo "✓ 获取到 " . count($messages->getData()) . " 条历史消息\n";
    
    // 重命名会话
    $renamedConversation = $chatClient->renameConversation(
        $conversationId, 
        'AI 技术讨论', 
        false, 
        'user-123'
    );
    echo "✓ 会话重命名成功: " . $renamedConversation->getName() . "\n\n";
    
} catch (Exception $e) {
    echo "✗ 会话管理失败: " . $e->getMessage() . "\n\n";
}

// 3. 消息反馈示例
echo "3. 消息反馈示例...\n";

try {
    $feedbackMessage = ChatMessage::create('请评价一下这个回答的质量', 'user-123')
        ->withResponseMode(ResponseMode::BLOCKING);
    
    $feedbackResponse = $chatClient->sendChatMessage($feedbackMessage);
    $messageId = $feedbackResponse->getMessageId();
    
    // 发送点赞反馈
    $feedback = $chatClient->feedbackMessage(
        $messageId, 
        'like', 
        'user-123', 
        '这个回答很有帮助'
    );
    
    if ($feedback->isSuccess()) {
        echo "✓ 消息反馈发送成功\n";
    }
    
    // 获取建议问题
    $suggestedQuestions = $chatClient->getSuggestedQuestions($messageId, 'user-123');
    echo "✓ 获取到 " . count($suggestedQuestions->getData()) . " 个建议问题\n\n";
    
} catch (Exception $e) {
    echo "✗ 消息反馈失败: " . $e->getMessage() . "\n\n";
}

// 4. 流式处理高级示例
echo "4. 流式处理高级示例...\n";

$streamMessage = ChatMessage::create('请写一篇关于环保的文章', 'user-123')
    ->withResponseMode(ResponseMode::STREAMING);

$advancedCallback = new ChatStreamCallback();
$advancedCallback
    ->onMessage(function($event) {
        // 实时显示生成的内容
        echo $event->getAnswer();
        flush(); // 立即输出
    })
    ->onMessageEnd(function($event) {
        echo "\n\n✓ 文章生成完成\n";
        echo "✓ 消息ID: " . $event->getMessageId() . "\n";
        echo "✓ 会话ID: " . $event->getConversationId() . "\n";
    })
    ->onError(function($event) {
        echo "\n✗ 生成过程中出现错误: " . $event->getMessage() . "\n";
    })
    ->onException(function($exception) {
        echo "\n✗ 发生异常: " . $exception->getMessage() . "\n";
    });

try {
    $chatClient->sendChatMessageStream($streamMessage, $advancedCallback);
    echo "✓ 流式处理完成\n\n";
} catch (Exception $e) {
    echo "✗ 流式处理失败: " . $e->getMessage() . "\n\n";
}

// 5. 错误处理示例
echo "5. 错误处理示例...\n";

try {
    // 故意使用错误的API密钥来演示错误处理
    $errorClient = DifyClientFactory::createChatClient($baseUrl, 'invalid-api-key');
    $errorMessage = ChatMessage::create('测试错误处理', 'user-123');
    $errorClient->sendChatMessage($errorMessage);
} catch (\Kunfeng\Dify\Exception\DifyApiException $e) {
    echo "✓ 捕获到API异常: " . $e->getMessage() . "\n";
    echo "✓ 状态码: " . $e->getStatusCode() . "\n";
    echo "✓ 响应数据: " . json_encode($e->getResponseData()) . "\n\n";
} catch (Exception $e) {
    echo "✓ 捕获到其他异常: " . $e->getMessage() . "\n\n";
}

// 6. 资源清理
echo "6. 资源清理...\n";
$client->close();
$chatClient->close();
echo "✓ 资源清理完成\n\n";

echo "=== 高级示例完成 ===\n";
